import json
from typing import Dict, List


def evaluate(datasets: str, result: Dict[int, List[int]], recall_rank=[1, 5, 20, 50, -1], cold_start=False):
    label = json.load(open(f'{datasets}/interaction_data/interaction_test{"_cold" if cold_start else ""}.json', 'rt'))
    train_data = json.load(open(f'{datasets}/interaction_data/interaction_train.json', 'rt'))
    user_list = json.load(open(f'{datasets}/user_data/user_list.json', 'rt'))

    total_cnt = 0
    total_hit = [0] * len(recall_rank)

    for user_id, interact_seq in label.items():
        user_id = int(user_id)

        for interact in interact_seq:
            total_cnt += 1
            book_id = interact['book_id']

            if user_id not in result:
                sid = user_list[str(user_id)]
                print(f'{sid} not in, len = {len(train_data[str(user_id)])}')
                continue

            for i, rank in enumerate(recall_rank):
                if rank > 0 and book_id in result[user_id][:rank]:
                    total_hit[i] += 1
                elif rank <= 0 and book_id in result[user_id]:
                    total_hit[i] += 1

    for i in range(len(recall_rank)):
        print(f'Hit@{recall_rank[i]}: {total_hit[i]}/{total_cnt} HR@{recall_rank[i]}: {total_hit[i]/total_cnt}')
